package com.dexter.year2023.charpter4_stack.level1;

/**
 * 用链表实现Stack
 *
 * @author Dexter
 */
class Demo3ListStack<T> {
    // 定义链表
    class Node<T> {
        public T t;
        public Node next;
    }

    public Node<T> head;

    // 构造方法，初始化头结点
    Demo3ListStack() {
        head = null;
    }

    // 栈空
    public boolean isEmpty() {
        if (head == null) {
            return true;
        } else {
            return false;
        }
    }

    // 栈顶
    public T peek() {
        if (head == null) {
            return null;
        } else {
            T t = head.t;
            return t;
        }
    }

    // 入栈
    public void push(T t) {
        if (t == null) {
            throw new NullPointerException("参数不能为空");
        }
        if (head == null) {
            // 成为头结点
            head = new Node<>();
            head.t = t;
            head.next = null;
        } else {
            // 暂存当前头结点信息
            Node<T> temp = head;
            head = new Node<>();
            head.t = t;
            head.next = temp;
        }
    }

    // 出栈
    public T pop() {
        if (head == null) {
            return null;
        }
        T t = head.t;
        head = head.next;
        return t;
    }

    public static void main(String[] args) {
        // 测试用例
        Demo3ListStack<String> stack = new Demo3ListStack<>();
        System.out.println(stack.peek());
        System.out.println(stack.isEmpty());
        stack.push("Stephen Curry");
        stack.push("Klay Thompson");
        stack.push("Draymond Green");
        System.out.println(stack.pop());  // Draymond Green
        System.out.println(stack.isEmpty());
        System.out.println(stack.peek()); // Klay Thompson
    }
}
